const express = require('express')
const app = express()
app.listen(3000,function(){
console.log('3000端口开启了，可以访问: http://localhost:3000')
})
//图片
app.use(express.urlencoded({extended:false}));
app.use('/static',express.static('static'))
const serveFavicon = require('serve-favicon')
app.use(serveFavicon('favicon.ico'))



const fs = require('fs')
let F = fs.readFileSync('persons.json','utf8')
F = JSON.parse(F)
console.log(F)
const path = require('path')
const { serialize } = require('v8')
const timeStamp = require('time-stamp')

//时间
app.use(function(req,res,next){
    let d = new Date()
    let year = d.getFullYear()
    let month = d.getMonth()+1
    let day =d.getDate()
    let h = d.getHours()
    let m = d.getMinutes()
    let s = d.getSeconds()

    

    req.time = `${year}年${month}月${day}日${h}时${m}分${m}秒`
    next()

})

app.get('/login',(req,res)=>{
    let fill = path.join(__dirname,'login.html')
    res.sendFile(fill)
})

app.post('/login',(req,res)=>{
   
    console.log(req.body);
    let D = req.body
    let ND = JSON.stringify(D)
    console.log(ND);

   let NF =  F.find(function(item){
        return item.username === D.tel && item.password === D.pass
   })
   if(NF){
    res.send('登陆成功'+ req.time)

}else{
    res.send('用户名或密码错误')
}
  
}) 
//注册
app.get('/register',(req,res)=>{
    let fill = path.join(__dirname,'register.html')
    res.sendFile(fill)
})
app.post('/register', (req, res) => {
    let { username = '', password = '', repwd = '' } = req.body
    console.log(username,password,repwd);
    let reg = /^\s+|\s+$/g
    username = username.replace(reg, '')
    if (username == '' || !password || !repwd) {
        res.send('请传递必要参数')
        return 
    }
    if( password != repwd ){
        res.send('两次密码不一致')
        return
    }
    let persons = fs.readFileSync('persons.json', 'utf8')
    persons = JSON.parse(persons) 
    let index = persons.findIndex(item => { 
        return item.username == username 
    })
    let time =timeStamp('YYYY-MM-DD HH:mm:ss')
    if (index != -1) {
        res.send('用户名已存在')
        return
    } else {
        res.send('注册成功' )
        persons.push({ username,password,time })
       
        persons = JSON.stringify(persons)
        fs.writeFileSync('persons.json', persons )
        return
    }
})


